<template>
  <div class="mate-remote-outer">
    <div><Avatar :src="userInfo.avatar" /></div>
    <div>{{ userInfo.name }}</div>
    <div>
      <Button v-if="hasToLogin" @click="gotoLogin">进入登录页面</Button>
    </div>
    <Row style="padding: 12px">
      <Col :span="12">
        <div style="display: flex">
          <!-- 面包屑 -->
          <div style="flex-grow: 1; line-height: 32px">
            <span
              v-for="(item, i) in fileNav"
              :key="item.id"
              @click="clickFolder(item, i)"
              style="padding: 0 2px; cursor: pointer"
            >
              / {{ item.name }}
            </span>
          </div>
          <!-- 刷新按钮 -->
          <div>
            <Button @click="newFile(curFileId)">新建</Button>
            <Button @click="getFileList(curFileId)">刷新</Button>
          </div>
        </div>
        <Table :columns="columns1" :data="fileList">
          <template slot-scope="{ row }" slot="name">
            <span @click="viewDetail(row)" style="cursor: pointer"> {{ row.name }} </span>
          </template>
        </Table>
      </Col>
      <Col :span="12">
        <Tabs :value="curTab">
          <TabPane label="标签一" name="name1">
            <!-- 属性项 -->
            <div
              v-for="item in fileKeys"
              :key="item"
              style="display: flex; height: 32px; line-height: 32px; font-size: 14px"
            >
              <div style="width: 120px; text-align: right; padding: 0 8px">{{ item }}:</div>
              <div v-if="item != 'url'">{{ fileInfo[item] }}</div>
              <div v-if="item == 'url'"><Input :value="fileInfo[item]" /></div>
            </div>
            <!-- 操作按钮 -->
            <div style="display: flex; height: 32px; line-height: 32px; font-size: 14px">
              <div style="width: 120px; text-align: right; padding: 0 8px">操作:</div>
              <Button @click="loadFile(fileInfo.file_id)">加载</Button>
              <Button @click="queryData">查询</Button>
            </div>
          </TabPane>
          <TabPane label="标签二" name="name2">
            <div style="padding-left: 12px">
              <div>文件名：</div>
              <Input v-model="newFileName" />
              <div>文件内容：</div>
              <Input v-model="newFileContent" type="textarea" :rows="8" />
            </div>
            <div>
              <Button @click="createFile(curFileId)">保存</Button>
            </div>
          </TabPane>
          <TabPane label="标签三" name="name3">
            <hao-123 :linkList="showData"></hao-123>
          </TabPane>
        </Tabs>
      </Col>
    </Row>
  </div>
</template>

<script>
import axios from 'axios';
import Hao123 from './common/HaoRemote.vue';
export default {
  components: { Hao123 },
  name: 'MateRemote',
  data() {
    return {
      // 新建功能
      newFileName: 'abc.txt',
      newFileContent: 'abcabcabcabc',

      curTab: 'name1',

      curFileId: 'root',
      fileNav: [{ name: 'root', file_id: 'root' }],
      token: null,
      hasToLogin: false,
      src: '',

      userInfo: {
        id: null,
        name: null,
        avatar: null,
        phone: null,
      },

      fileList: [],
      fileInfo: {},
      fileUrl: '',
      fileKeys: ['file_id', 'name', 'type', 'category', 'url', 'size', 'mime_type', 'created_at', 'updated_at'],
      columns1: [
        {
          title: 'name',
          key: 'name',
          slot: 'name',
        },
        {
          title: 'type',
          key: 'type',
        },
        {
          title: 'size',
          key: 'size',
        },
        {
          title: 'mime_type',
          key: 'mime_type',
        },
      ],
    };
  },
  computed: {
    showData() {
      let retObj = {};
      if (this.newFileContent) {
        try {
          retObj = JSON.parse(this.newFileContent);
        } catch (error) {
          console.log(error);
        }
      }
      return retObj;
    },
  },
  methods: {
    createFile(curFileId) {
      const body = {
        parent_file_id: curFileId,
        name: this.newFileName,
        content: this.newFileContent,
      };
      axios.post('/main/createFile', body).then(res => {
        if (res.status == 200) {
          this.$Message.success(JSON.stringify(res.data));
          this.getFileList(curFileId);
        } else {
          // res.data.code != 'AccessTokenExpired'
          //   this.autoLogin();
        }
      });
    },
    newFile(curFileId) {
      this.curTab = 'name2';
    },
    // 查询数据示例
    queryData(file_id) {
      const body = {
        file_id,
      };
      axios.post('/main/queryData', body).then(res => {
        if (res.status == 200) {
          this.$Message.success(JSON.stringify(res.data));
        } else {
          // res.data.code != 'AccessTokenExpired'
          //   this.autoLogin();
        }
      });
    },

    clickFolder(folderObj, i) {
      if (this.curFileId == folderObj.file_id) {
        return;
      } else {
        this.curFileId = folderObj.file_id;
      }
      this.getFileList(folderObj.file_id);
      this.fileNav = this.fileNav.slice(0, i + 1);
    },

    // 调用后台加载命令，同步文件到user目录
    loadFile(file_id) {
      const body = {
        file_id,
      };
      axios.post('/main/loadFile', body).then(res => {
        if (res.status == 200) {
          this.$Message.success('加载成功');
        } else {
          // res.data.code != 'AccessTokenExpired'
          //   this.autoLogin();
        }
      });
    },

    loadFileContent(file) {
      const { file_id, name, mime_type } = file;
      const tmpBody = { file_id, name, mime_type, url: this.fileUrl };
      axios.post('/main/getFileContent', tmpBody).then(res => {
        if (res.status == 200) {
          this.newFileName = name;
          if (res.headers['content-type'] == 'application/json;charset=UTF-8') {
            this.newFileContent = JSON.stringify(res.data, null, 2);
          } else {
            this.newFileContent = res.data;
          }
          // this.fileInfo = res.data;
        } else {
          // res.data.code != 'AccessTokenExpired'
          //   this.autoLogin();
        }
      });
    },

    // 获取文件信息
    viewDetail(file) {
      if (this.curFileId == file.file_id) {
        return;
      } else {
        this.curFileId = file.file_id;
      }

      if (file.type == 'folder') {
        this.getFileList(file.file_id);

        const { name, file_id } = file;
        this.fileNav.push({ name, file_id });
        // return;
      }

      const body = {
        file_id: file.file_id,
      };
      const reqList = [axios.post('/main/openFile_get', body), axios.post('/main/openFile_getDownloadUrl', body)];
      Promise.all(reqList).then(res => {
        if (res[0].status == 200) {
          this.fileInfo = res[0].data;
        } else {
          // res.data.code != 'AccessTokenExpired'
          //   this.autoLogin();
        }
        if (res[1].status == 200 && res[1].data.url) {
          this.fileUrl = res[1].data.url;
        }

        if (file.type == 'file') {
          this.loadFileContent(file);
        }
      });
    },

    // 获取文件列表
    getFileList(parent_file_id) {
      const body = { parent_file_id };
      axios.post('/main/openFile_list', body).then(res => {
        if (res.status == 200) {
          this.fileList = res.data.items;
        } else {
          this.$Notice.error({
            title: res.data.error,
            desc: res.data.message,
          });
          // res.data.code != 'AccessTokenExpired'
          //   this.autoLogin();
        }
      });
    },

    // 检测是否登录，查询用户信息
    checkLogin() {
      axios.get('/main/users_info').then(res => {
        if (res.status == 200 && res.data.id) {
          Object.assign(this.userInfo, res.data);
          this.getFileList('root');
        } else {
          // res.data.code != 'AccessTokenExpired'
          this.token = null;
          this.autoLogin();
        }
      });
    },

    // 通过code获取token
    autoLogin() {
      const query = this.$route.query;
      if (query.code) {
        axios.post('/main/access_token', { code: query.code }).then(res => {
          if (res.data && res.data.token && res.data.token != 'null') {
            this.token = res.data.token;
            this.checkLogin();
          } else {
            this.hasToLogin = true;
          }
        });
      } else {
        this.hasToLogin = true;
      }
    },

    // 跳转到登录页面
    gotoLogin() {
      const baseHost = 'https://openapi.alipan.com/oauth/authorize';
      const client_id = '3d9d7f99e56647ab8fad95ea8713ae28';
      const redirect_uri = 'http://localhost:8082/report-boot/mateRemote';
      const scope = 'user:base,file:all:write';
      this.src = `${baseHost}?client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${scope}`;
      //   this.$refs.iframeRef.src = this.src;
      window.location.href = this.src;
    },
  },

  mounted() {
    this.checkLogin();
  },
};
</script>

<style scoped>
</style>
